package mwa.cs.hh.ctrl;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import mwa.cs.dao.AddressDAO;
import mwa.cs.dao.RouteDetailDAO;
import mwa.cs.database.Database;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;

/**
 * Servlet implementation class AddSequenceRouteDetailSrvl
 */
public class CS35001Srvl extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private int vnSiteId;
	private int vnUserId;
	private int vnZoneId;
	private int vnRouteId;
	private int vnSequenceNew;
	private int vnSequenceOld;
	private String vaAccount;
	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public CS35001Srvl() {
		super();
		// TODO Auto-generated constructor stub
	}

	
	public void processRequest(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/JSON");
		vnSiteId = Integer.parseInt(request.getSession().getAttribute("site_id").toString());
		vnUserId = Integer.parseInt(request.getSession().getAttribute("user_id").toString());
		if(request.getParameter("process_type").equals("getDataTable")){
			getDataTable(request, response);
		}else if(request.getParameter("process_type").equals("getLastSequence")){
			getLastSequence(request, response);
		}else if(request.getParameter("process_type").equals("addSequence")){
			addSequence(request, response);
		}else if (request.getParameter("process_type").equals("goToAddSequence")) {
            goToAddSequence(request, response);
		} 
			
		
	}
	
	
	@SuppressWarnings("unchecked")
	public void getDataTable(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		if(request.getParameter("vnZoneId")!=null){
			vnZoneId = Integer.parseInt(request.getParameter("vnZoneId"));
		}else{
			vnZoneId = 0;
		}
		if(request.getParameter("vnRouteId")!=null){
			vnRouteId = Integer.parseInt(request.getParameter("vnRouteId"));
		}else{
			vnRouteId = 0;
		}
		String vaAccountSearching = request.getParameter("sSearch_0").trim();
	    String vaAccountOldSearching = request.getParameter("sSearch_1").trim();
	    String vaHomeNumberSearching = request.getParameter("sSearch_2").trim();
	    //String vaNameSearching = new String(request.getParameter("sSearch_3").trim().getBytes("ISO-8859-1"), "UTF-8");
	    String vaNameSearching = new String(request.getParameter("sSearch_3").trim());
	    String[] vaColumns = { "account","account","account_old","fname", "home_number","account","account" };
		int vnStart = Integer.parseInt(request.getParameter("iDisplayStart")); // 0
	    int vnAmount = Integer.parseInt(request.getParameter("iDisplayLength")); // 10
	    int vnSortColumn = Integer.parseInt(request.getParameter("iSortCol_0")); // 0, 1, 2, 3
	    String vaSortDirection = request.getParameter("sSortDir_0"); // asc, desc
	    
    	Database db = new Database();
    	RouteDetailDAO voRouteDetailDAO = new RouteDetailDAO(db);
    	PrintWriter voOut = response.getWriter();
    	List<Map<String, Object>> voList = new ArrayList<Map<String, Object>>();
		Map<String, Object> voMap = new HashMap<String, Object>();
		
		int vnTotalRecords = voRouteDetailDAO.getCountAddSequenceRouteDetail(vnSiteId, vnZoneId, vnRouteId, vaAccountSearching, 
				vaAccountOldSearching, vaHomeNumberSearching, vaNameSearching,vaColumns[vnSortColumn], vaSortDirection);
		int vnTotalDisplayRecords =0;
		
		int vnEnd = vnStart + vnAmount;
		
		if(vnAmount != -1 ){
			
				voList = voRouteDetailDAO.findAddSequenceRouteDetailByLength(vnSiteId, vnZoneId, vnRouteId, vaAccountSearching, 
	    				vaAccountOldSearching, vaHomeNumberSearching, vaNameSearching,vaColumns[vnSortColumn], vaSortDirection, vnStart, vnEnd);
				vnTotalDisplayRecords = voRouteDetailDAO.getCountAddSequenceRouteDetail(vnSiteId, vnZoneId, vnRouteId, vaAccountSearching, 
	    				vaAccountOldSearching, vaHomeNumberSearching, vaNameSearching,vaColumns[vnSortColumn], vaSortDirection);
			
		}else{
			
				voList = voRouteDetailDAO.findAddSequenceRouteDetail(vnSiteId, vnZoneId, vnRouteId, vaAccountSearching, 
	    				vaAccountOldSearching, vaHomeNumberSearching, vaNameSearching,vaColumns[vnSortColumn], vaSortDirection);
				vnTotalDisplayRecords = vnTotalRecords;
			
		}
		
		JSONObject voObject = new JSONObject();
	    JSONArray voListData = new JSONArray();
	    JSONArray voArray = new JSONArray();
	    AddressDAO voAddress = new AddressDAO(db);
	    for (int i = 0; i < voList.size(); i++) {
			voArray = new JSONArray();
			 voMap = voList.get(i);
			 voArray.add((String) ""+(i+1));
			 voArray.add((String) ""+voMap.get("ACCOUNT"));
			 if(voMap.get("ACCOUNT_OLD") == null){
				 voArray.add((String) ""); 
			 }else{
				 voArray.add((String) ""+voMap.get("ACCOUNT_OLD")); 
			 }
			 voArray.add((String) ""+voMap.get("NAME"));
			 String vaHomeNumber = (String) voMap.get("HOME_NUMBER");
	            if (vaHomeNumber == null){ vaHomeNumber = "";}
	            String vaAddress = (String) voMap.get("ADDRESS");
	            if (vaAddress == null) {vaAddress = "";}
	            String vaProvinceCode = (String) voMap.get("PROVINCE_CODE");
	            String vaProvince = voAddress.getProvinceName(vaProvinceCode);
	            if (vaProvince == null) {vaProvince = "";}
	            String vaDistrictCode = (String) voMap.get("DISTRICT_CODE");
	            String vaDistrict = voAddress.getDistrictName(vaProvinceCode, vaDistrictCode);
	            if (vaDistrict == null) {vaDistrict = "";}
	            String vaCityCode = (String) voMap.get("CITY_CODE");
	            String vaCity = voAddress.getCityName(vaProvinceCode, vaDistrictCode, vaCityCode);
	            if (vaCity == null) {vaCity = "";}
	            String vaPostCode = (String) voMap.get("POST_CODE");
	            if (vaPostCode == null) {vaPostCode = "";}
	            String address = vaHomeNumber + " " + vaAddress + " " 
	    	            + vaCity + " " + vaDistrict + " " + vaProvince + " " + vaPostCode;
	            voArray.add(address);
	            voArray.add((String) ""+voMap.get("ACCOUNT"));
	            voArray.add((String) ""+voMap.get("ACCOUNT"));
			 voListData.add(voArray);
		 }
		 
		    voObject.put("iTotalRecords", vnTotalRecords);
	        voObject.put("iTotalDisplayRecords", vnTotalDisplayRecords);
	        voObject.put("aaData", voListData);
	        voOut.print(voObject.toJSONString());
		
	
	}
	
	@SuppressWarnings("unchecked")
	public void getLastSequence(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		PrintWriter voOut = response.getWriter();
		JSONObject voObject = new JSONObject();
		Database db = new Database();
    	RouteDetailDAO voRouteDetailDAO = new RouteDetailDAO(db);

		if(request.getParameter("vnZoneId")!=null){
			vnZoneId = Integer.parseInt(request.getParameter("vnZoneId"));
		}else{
			vnZoneId = 0;
		}
		if(request.getParameter("vnRouteId")!=null){
			vnRouteId = Integer.parseInt(request.getParameter("vnRouteId"));
		}else{
			vnRouteId = 0;
		}
		
		int lastSequence = voRouteDetailDAO.getLastSequenceRouteDetail(vnSiteId, vnZoneId, vnRouteId);
		voObject.put("lastSequence", lastSequence);
		voOut.print(voObject.toJSONString());
		
	}
	
	public void addSequence(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		Database db = new Database();
    	RouteDetailDAO voRouteDetailDAO = new RouteDetailDAO(db);

		if(request.getParameter("vnZoneId")!=null){
			vnZoneId = Integer.parseInt(request.getParameter("vnZoneId"));
		}else{
			vnZoneId = 0;
		}
		if(request.getParameter("vnRouteId")!=null){
			vnRouteId = Integer.parseInt(request.getParameter("vnRouteId"));
		}else{
			vnRouteId = 0;
		}
		if(request.getParameter("vnSequenceNew")!=null){
			vnSequenceNew = Integer.parseInt(request.getParameter("vnSequenceNew"));
		}else{
			vnSequenceNew = 0;
		}
		if(request.getParameter("vnSequenceOld")!=null){
			vnSequenceOld = Integer.parseInt(request.getParameter("vnSequenceOld"));
		}else{
			vnSequenceOld = 0;
		}
		vaAccount = request.getParameter("vaAccount");
		voRouteDetailDAO.updateAddSequenceRouteDetail(vnUserId, vnSiteId, vnZoneId, vnRouteId, vnSequenceNew, vnSequenceOld, vaAccount);
		db.commit();
		db.close();
		
	}
	public void goToAddSequence(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		
		vnZoneId = 0;
		vnRouteId = 0;
		vnSiteId = Integer.parseInt(request.getSession().getAttribute("site_id").toString());

		if (request.getParameter("zone_id") != null) {
			vnZoneId = Integer.parseInt(request.getParameter("zone_id"));
		}
		if (request.getParameter("route_id") != null) {
			vnRouteId = Integer.parseInt(request.getParameter("route_id"));
		}
		
		String vaZoneName = request.getParameter("zone_name");
		String vaRouteDescription = request
				.getParameter("route_description");
		request.setAttribute("vnZoneId", vnZoneId);
		request.setAttribute("vnRouteId", vnRouteId);
		request.setAttribute("vaZoneName", vaZoneName);
		request.setAttribute("vaRouteDescription", vaRouteDescription);

		RequestDispatcher voRequestDispatcher = request
				.getRequestDispatcher("CS35001.jsp");
		voRequestDispatcher.forward(request, response);

	}
	
	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}

}
